package com.hsgene.pay.controller;

import com.hsgene.common.util.character.CharactersConstant;
import com.hsgene.common.util.exception.ErrorCode;
import com.hsgene.common.util.resolver.IgnoreUserToken;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.order.constants.PayType;
import com.hsgene.order.constants.v1.PaymentBusinessType;
import com.hsgene.order.exception.OrderErrorCode;
import com.hsgene.pay.domain.PayMethod;
import com.hsgene.pay.exception.PayErrorCode;
import com.hsgene.pay.service.OrderPayService;
import com.hsgene.pay.service.support.QrCodeSupport;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单支付
 *
 * @author wxf
 * @date 2018/8/13 13:53
 **/
@RestController
@RequestMapping("/v1.0/genetic/testing/pay/")
public class OrderPayController {
    /**
     * Log
     */
    private static Logger LOGGER = LogManager.getLogger(OrderPayController.class);

    @Autowired
    private OrderPayService orderPayService;

    @Value("${pay.callback.field}")
    private String payCallbackField;

    /**
     * 订单支付
     *
     * @param orderId      订单id
     * @param payType      支付类型
     * @param payAmount    支付金额(单位分)
     * @param businessType 支付业务类型（1：基因检测；2：基因检测补款）
     * @return
     */
    @PostMapping("order_pay")
    public ApiResult orderPay(
            @RequestParam("orderId") String orderId,
            @RequestParam("payType") String payType,
            @RequestParam("payAmount") Integer payAmount,
            @RequestParam(name = "businessType", defaultValue = "1") Integer businessType,
            HttpServletResponse response) {
        try {
            LOGGER.info("pay info----orderId:" + orderId + ",payType:" + payType + ",payAmount:" + payAmount);
            ApiResult<Map<String, Object>> payResult = orderPayService.orderPay(orderId, payType, payAmount, PaymentBusinessType.getEnum(businessType));
            if (!payResult.isSucc()) {
                return payResult;
            }
            Map<String, Object> result = payResult.getData();
            if (result == null || result.isEmpty()) {
                LOGGER.error("pay info is get failed...");
                return ApiResult.fail(PayErrorCode.QUERY_ORDER_PAY_INFO_IS_ERROR);
            }
            if (payType.equals(PayType.CHINAUMS_QR.getCode())) {
                //返回支付二维码
                return QrCodeSupport.getPayCode(response, result);
            }
            return ApiResult.succ(result);
        } catch (Exception e) {
            LOGGER.error("pay order info is error", e);
            return ApiResult.fail(PayErrorCode.ORDER_PAY_IS_ERROR);
        }
    }

    /**
     * 支付回调
     *
     * @param request
     * @param response
     */
    @PostMapping("callback")
    @IgnoreUserToken
    public void updateOrderStatus(HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("====== 开始处理支付中心通知 ======");
        String[] arraysStr = payCallbackField.split(CharactersConstant.COMMA_EN);
        Map<String, Object> paramMap = new HashMap<>();
        Map<String, String[]> map = request.getParameterMap();
        Arrays.stream(arraysStr).forEach(str -> {
            if (map.get(str) != null) {
                paramMap.put(str, map.get(str)[0]);
            }
        });
        LOGGER.info("支付中心通知请求参数,paramMap={}", paramMap);
        String result = orderPayService.payCallback(paramMap);
        outResult(response, result);
        LOGGER.info("====== 支付中心通知处理完成 ======,支付结果：" + result);
    }

    private void outResult(HttpServletResponse response, String content) {
        response.setContentType("text/html");
        PrintWriter pw;
        try {
            pw = response.getWriter();
            pw.print(content);
            LOGGER.info("response pay complete.");
        } catch (IOException e) {
            LOGGER.error(e + "response pay write exception.");
        }
    }

    /**
     * 查询支付订单信息
     *
     * @param orderId    订单id
     * @param payOrderId 支付id
     * @return
     */
    @GetMapping("query_order")
    public ApiResult<Map<String, Object>> queryPayOrder(String orderId, String payOrderId) {
        try {
            Map<String, Object> result = orderPayService.queryPayOrder(orderId, payOrderId);
            return new ApiResult(200, "success", "query pay order info is success", result);
        } catch (Exception e) {
            LOGGER.error("query pay order info is error", e);
            return ApiResult.fail(PayErrorCode.QUERY_PAY_ORDER_IS_ERROR);
        }
    }

    /**
     * @param
     * @return com.hsgene.common.util.result.ApiResult<java.util.List>
     * @description 获取支付方式列表
     * @author maodi
     * @createDate 2018/9/30 10:48
     */
    @GetMapping("methods")
    public ApiResult<List> getPayMethodList() {
        try {
            List<PayMethod> payMethodList = orderPayService.queryPayMethodList();
            if (payMethodList == null || payMethodList.size() < 1) {
                return ApiResult.fail(PayErrorCode.PAY_METHOD_IS_NULL);
            }
            return ApiResult.succ(payMethodList);
        } catch (Exception e) {
            LOGGER.error("query pay method info is error", e);
            return ApiResult.fail(PayErrorCode.QUERY_PAY_METHOD_IS_ERROR);
        }
    }
}
